package com.atguigu.gulimall.order.web;


import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.SubmitRespVo;
import org.bouncycastle.math.raw.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        System.out.println(confirmVo.toString());
        model.addAttribute("orderConfirmData", confirmVo);
        return "confirm";
    }


    @PostMapping("/submitorder")
    public String submitOrder(OrderSubmitVo submitVo, Model model, RedirectAttributes attributes) throws NoStockException {
        //创建订单，验令牌
        SubmitRespVo respVo = orderService.submitOrder(submitVo);

        if(respVo.getCode()==0){
            //创建成功，去支付页面
            model.addAttribute("submitOrderResp",respVo);
            return "pay";
        }else{
            String msg = "下单失败=>";
            //创建失败，重新回到确认页面
            switch (respVo.getCode()){
                case 1: msg+="令牌验证失败";break;
                case 2: msg+="验价失败";break;
                case 3: msg+="库存锁定失败";break;

            }
            attributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }



}
